//
//  NMNMZRRDViewController.m
//  HNJYB
//
//  Created by Mag1cPanda on 2017/3/24.
//  Copyright © 2017年 Mag1cPanda. All rights reserved.
//

#import "NMNMZRRDViewController.h"
#import "DESCript.h"
#import "JCAlertView.h"
#import "JFCreateProtocolVC.h"
#import "WaitDutyViewController.h"
#import "SRBlockButton.h"
#import "WFTKViewController.h"
#import "NMZRRDGroup.h"

@interface NMNMZRRDViewController ()
{
    UIScrollView *scroll;
    JCAlertView *jcAlert;
    JCAlertView *endAlert;
    
    NSMutableDictionary *bean;
    
    NSString *jfDutyType;
    NSString *yfDutyType;
    
    BOOL isArgue;
    
    NSString *jfLegalabbreviation;
    NSString *yfLegalabbreviation;
}
@property (nonatomic, strong) NMZRRDGroup *partyAGroup;
@property (nonatomic, strong) NMZRRDGroup *partyBGroup;
@end

@implementation NMNMZRRDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"责任认定";
    bean = [NSMutableDictionary dictionary];
    jfLegalabbreviation = @"";
    yfLegalabbreviation = @"";
    NSString *appcaseno = GlobleInstance.appcaseno;
    [bean setValue:appcaseno forKey:@"appcaseno"];
    
    NSString *imagelon = [NSString stringWithFormat:@"%f", GlobleInstance.imagelon];
    NSString *imagelat = [NSString stringWithFormat:@"%f", GlobleInstance.imagelat];
    [bean setValue:imagelon forKey:@"caselon"];
    [bean setValue:imagelat forKey:@"caselat"];
    [bean setValue:GlobleInstance.imageaddress forKey:@"accidentplace"];
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    //输出格式为：2010-10-27 10:22:13
    NSLog(@"%@", currentDateStr);
    [bean setValue:currentDateStr forKey:@"alarmtime"];
    [bean setValue:GlobleInstance.areaid forKey:@"areaid"];
    
    [bean setValue:GlobleInstance.userflag forKey:@"username"];
    NSString *pwd = [UserDefaultsUtil getDataForKey:@"password"];
    pwd = [DESCript encrypt:pwd encryptOrDecrypt:kCCEncrypt key:[Util getKey]];
    [bean setValue:pwd forKey:@"password"];
    
    NSLog(@"事故形态 -> %@", _selectedItem);
    
    NSMutableArray *selectArr = [NSMutableArray array];
    for (int i = 0; i < _selectedItem.count; i++)
    {
        NSString *str = _selectedItem[i];
        if ([str isEqualToString:@"1"])
        {
            [selectArr addObject:[NSString stringWithFormat:@"%d", i + 1]];
        }
    }
    NSString *accidenttype = [selectArr componentsJoinedByString:@","];
    NSLog(@"accidenttype -> %@", accidenttype);
    NSString *token = [NSString stringWithFormat:@"%@", GlobleInstance.token];
    [bean setValue:token forKey:@"token"];
    [bean setValue:accidenttype forKey:@"accidenttype"];
    
    if (!_caseDes)
    {
        _caseDes = @"";
    }
    
    [bean setValue:_caseDes forKey:@"accidentdes"];
    
    [self initScroll];
    
    //如果为历史案件Push，则加载历史案件数据
    if (_isHistoryPush)
    {
        self.jfModel = [[InfoModel alloc] init];
        self.yfModel = [[InfoModel alloc] init];
        [self loadHistoryData];
    }

    
}

#pragma mark - 初始化Scroll
- (void)initScroll
{
    scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    [self.view addSubview:scroll];
    
    __unsafe_unretained typeof(self) weakSelf = self;
    //机动车方
    _partyAGroup = [[NMZRRDGroup alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 400) groupId:@"partyAGroup"];
    _partyAGroup.title = @"甲方驾驶人及车辆信息";
    _partyAGroup.xmView.contentField.text = _jfModel.name;
    _partyAGroup.lxdhView.contentField.text = _jfModel.phoneNum;
    
    UITapGestureRecognizer *tapA = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelDidTouched:)];
    [_partyAGroup.wftkLab addGestureRecognizer:tapA];
    
    _partyAGroup.block = ^(NSInteger index) {
        //全责
        if (index == 0)
        {
            weakSelf.partyBGroup.radio2.checked = YES;
            
            weakSelf.partyAGroup.wftkLab.userInteractionEnabled = YES;
            weakSelf.partyBGroup.wftkLab.userInteractionEnabled = NO;
            
            weakSelf.partyAGroup.wftkLab.text = @"请选择违法条款";
            weakSelf.partyBGroup.wftkLab.text = @"无责无需选择";
        }
        //无责
        if (index == 1)
        {
            weakSelf.partyBGroup.radio1.checked = YES;
            
            weakSelf.partyAGroup.wftkLab.userInteractionEnabled = NO;
            weakSelf.partyBGroup.wftkLab.userInteractionEnabled = YES;
            
            weakSelf.partyAGroup.wftkLab.text = @"无责无需选择";
            weakSelf.partyBGroup.wftkLab.text = @"请选择违法条款";
        }
        //同责
        if (index == 2)
        {
            weakSelf.partyBGroup.radio3.checked = YES;
            
            weakSelf.partyAGroup.wftkLab.userInteractionEnabled = YES;
            weakSelf.partyBGroup.wftkLab.userInteractionEnabled = YES;
            
            weakSelf.partyAGroup.wftkLab.text = @"请选择违法条款";
            weakSelf.partyBGroup.wftkLab.text = @"请选择违法条款";
        }
        if (index == 3)
        {
            //          weakSelf.partyBGroup.radio5.checked = YES;
        }
        if (index == 4)
        {
            //          weakSelf.partyBGroup.radio4.checked = YES;
        }
    };
    [scroll addSubview:_partyAGroup];
    
    
    //非机动车方
    _partyBGroup = [[NMZRRDGroup alloc] initWithFrame:CGRectMake(0, _partyAGroup.maxY, ScreenWidth, 400) groupId:@"partyBGroup"];
    _partyBGroup.title = @"乙方驾驶人及车辆信息";
    _partyBGroup.xmView.contentField.text = _yfModel.name;
    _partyBGroup.lxdhView.contentField.text = _yfModel.phoneNum;
    
    UITapGestureRecognizer *tapB = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelDidTouched:)];
    [_partyBGroup.wftkLab addGestureRecognizer:tapB];
    
    _partyBGroup.block = ^(NSInteger index) {
        //全责
        if (index == 0)
        {
            weakSelf.partyAGroup.radio2.checked = YES;
            
            weakSelf.partyAGroup.wftkLab.userInteractionEnabled = NO;
            weakSelf.partyBGroup.wftkLab.userInteractionEnabled = YES;
            
            weakSelf.partyAGroup.wftkView.contentField.placeholder = @"无责无需选择";
            weakSelf.partyBGroup.wftkView.contentField.placeholder = @"请选择违法条款";
        }
        //无责
        if (index == 1)
        {
            weakSelf.partyAGroup.radio1.checked = YES;
            
            weakSelf.partyAGroup.wftkLab.userInteractionEnabled = YES;
            weakSelf.partyBGroup.wftkLab.userInteractionEnabled = NO;
            
            weakSelf.partyAGroup.wftkView.contentField.placeholder = @"请选择违法条款";
            weakSelf.partyBGroup.wftkView.contentField.placeholder = @"无责无需选择";
        }
        //同责
        if (index == 2)
        {
            weakSelf.partyAGroup.radio3.checked = YES;
            
            weakSelf.partyAGroup.wftkLab.userInteractionEnabled = YES;
            weakSelf.partyBGroup.wftkLab.userInteractionEnabled = YES;
            
            weakSelf.partyAGroup.wftkView.contentField.placeholder = @"请选择违法条款";
            weakSelf.partyBGroup.wftkView.contentField.placeholder = @"请选择违法条款";
        }
        if (index == 3)
        {
            //          weakSelf.partyAGroup.radio5.checked = YES;
        }
        if (index == 4)
        {
            //          weakSelf.partyAGroup.radio4.checked = YES;
        }
        
    };
    [scroll addSubview:_partyBGroup];
    
    
    if (GlobleInstance.userType == AuxiliaryPolice) {
        _partyAGroup.zrlxView.hidden = YES;
        _partyAGroup.wftkView.hidden = YES;
        _partyAGroup.frame = CGRectMake(_partyAGroup.x, _partyAGroup.y, _partyAGroup.width, 250);
        
        _partyBGroup.zrlxView.hidden = YES;
        _partyBGroup.wftkView.hidden = YES;
        _partyBGroup.frame = CGRectMake(_partyBGroup.x, _partyAGroup.maxY + 10, _partyBGroup.width, 250);
    }
    
    
    UIButton *argueBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    argueBtn.frame = CGRectMake(10, _partyBGroup.maxY + 10, ScreenWidth - 20, 50);
    if (GlobleInstance.userType == TrafficPolice)
    {
        //交警
        [argueBtn setTitle:@"现场定责" forState:0];
    }
    else
    {
        //协警
        [argueBtn setTitle:@"远程定责" forState:0];
        _partyAGroup.wftkLab.userInteractionEnabled = NO;
        _partyBGroup.wftkLab.userInteractionEnabled = NO;
    }
    [argueBtn setTitleColor:[UIColor whiteColor] forState:0];
    [argueBtn addTarget:self action:@selector(argueBtnClicked) forControlEvents:1 << 6];
    argueBtn.backgroundColor = HNBlue;
    argueBtn.layer.cornerRadius = 5;
    [scroll addSubview:argueBtn];
    
    scroll.contentSize = CGSizeMake(ScreenWidth, argueBtn.maxY + 20);
}

#pragma mark - Label点击事件
-(void)labelDidTouched:(UITapGestureRecognizer *)tap
{
    UILabel *label = (UILabel *)tap.view;
    
    WFTKViewController *vc = [WFTKViewController new];
    
    if (label == _partyAGroup.wftkLab) {
        vc.block = ^(NSString *content, NSString *index){
            _partyAGroup.wftkLab.text = content;
            jfLegalabbreviation = index;
        };
    }
    
    else {
        vc.block = ^(NSString *content, NSString *index){
            _partyBGroup.wftkLab.text = content;
            yfLegalabbreviation = index;
        };
    }
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 加载数据(继续处理)
- (void)loadHistoryData
{
    NSMutableDictionary *historyBean = [NSMutableDictionary dictionary];
    [historyBean setValue:GlobleInstance.token forKey:@"token"];
    [historyBean setValue:GlobleInstance.userflag forKey:@"username"];
    [historyBean setValue:_casenumber forKey:@"casenumber"];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [LSHttpManager requestUrl:HNServiceURL serviceName:@"kckpjjAccidentDetails" parameters:historyBean complete:^(id result, ResultType resultType) {
        
        [hud hideAnimated:YES];
        if ([result[@"restate"] isEqualToString:@"1"])
        {
            NSLog(@"History -> %@", JsonResult);
            NSDictionary *data = result[@"data"];
            GlobleInstance.casehaptime = data[@"casehaptime"];
            NSArray *casecarlist = data[@"casecarlist"];
            NSDictionary *jfDic = casecarlist[0];
            NSDictionary *yfDic = casecarlist[1];
            
            self.jfModel.name = jfDic[@"carownname"];
            self.jfModel.phoneNum = jfDic[@"carownphone"];
            self.jfModel.carNum = jfDic[@"casecarno"];
            
            self.yfModel.name = yfDic[@"carownname"];
            self.yfModel.phoneNum = yfDic[@"carownphone"];
            self.yfModel.carNum = yfDic[@"casecarno"];
            
            _partyAGroup.xmView.contentField.text = _jfModel.name;
            _partyAGroup.lxdhView.contentField.text = _jfModel.phoneNum;
            
            _partyBGroup.xmView.contentField.text = _yfModel.name;
            _partyBGroup.lxdhView.contentField.text = _yfModel.phoneNum;
        }
        
    }];
}

#pragma mark - 有争议
- (void)argueBtnClicked
{
    isArgue = YES;
    if (!_partyAGroup.selectedIndex && GlobleInstance.userType == TrafficPolice)
    {
        SHOWALERT(@"请选择责任类型");
        return;
    }
    
    //违法条款条件判断
    if (GlobleInstance.userType == TrafficPolice)
    {
        if (_partyAGroup.radio1.checked) {
            if ([jfLegalabbreviation isEqualToString:@""]) {
                SHOWALERT(@"请选择甲方违法条款");
                return;
            }
        }
        
        if (_partyAGroup.radio2.checked) {
            if ([yfLegalabbreviation isEqualToString:@""]) {
                SHOWALERT(@"请选择乙方违法条款");
                return;
            }
        }
        
        if (_partyAGroup.radio3.checked) {
            if ([jfLegalabbreviation isEqualToString:@""]) {
                SHOWALERT(@"请选择甲方违法条款");
                return;
            }
            
            if ([yfLegalabbreviation isEqualToString:@""]) {
                SHOWALERT(@"请选择乙方违法条款");
                return;
            }
        }
    }
    
    if (GlobleInstance.userType == TrafficPolice)
    {
        //交警 -> 现场定责
        [bean setValue:@"3" forKey:@"disposetype"];
    }
    else
    {
        //协警 -> 远程定责
        _partyAGroup.selectedIndex = @""; //设为空字符串，避免为nil导致闪退
        _partyBGroup.selectedIndex = @""; //同上
        [bean setValue:@"2" forKey:@"disposetype"];
    }
    
    
    [self showAlertView];
}

#pragma mark - 无争议
- (void)confirmBtnClicked
{
    isArgue = NO;
    //交警账号没有选择责任类型时提示用户
    if (!_partyAGroup.selectedIndex)
    {
        SHOWALERT(@"请选择责任类型");
        return;
    }
    [bean setValue:@"1" forKey:@"disposetype"];
    [self showAlertView];
}

#pragma mark - 确认提示框
- (void)showAlertView
{
    UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 60, 200)];
    customView.backgroundColor = [UIColor whiteColor];
    customView.layer.cornerRadius = 5;
    customView.clipsToBounds = YES;
    
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(customView.width / 2 - 30, 20, 60, 60)];
    icon.image = [UIImage imageNamed:@"IP030"];
    [customView addSubview:icon];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + 20, customView.width, 20)];
    lab.font = HNFont(14);
    lab.text = @"确认提交吗？";
    lab.textColor = [UIColor darkGrayColor];
    lab.textAlignment = NSTextAlignmentCenter;
    [customView addSubview:lab];
    
    UIView *horizontalLine = [[UIView alloc] initWithFrame:CGRectMake(0, lab.maxY + 20, customView.width, 1)];
    horizontalLine.backgroundColor = RGB(235, 235, 235);
    [customView addSubview:horizontalLine];
    UIView *verticalLine = [[UIView alloc] initWithFrame:CGRectMake(customView.width / 2, lab.maxY + 20, 1, 60)];
    verticalLine.backgroundColor = RGB(235, 235, 235);
    [customView addSubview:verticalLine];
    
    UIColor *color = [UIColor blackColor];
    
    SRBlockButton *confirmBtn = [[SRBlockButton alloc] initWithFrame:CGRectMake(0, lab.maxY + 21, customView.width / 2, 60) title:@"确认" titleColor:color handleBlock:^(SRBlockButton *btn) {
        
        [jcAlert dismissWithCompletion:^{
            
            [bean setValue:_yfModel.carNum forKey:@"casecarno"];
            [bean setValue:_yfModel.phoneNum forKey:@"appphone"];
            
            NSArray *arr = @[ @{ @"carownname" : _jfModel.name,
                                 @"carownphone" : _jfModel.phoneNum,
                                 @"casecarno" : _jfModel.carNum,
                                 @"cartype" : _jfModel.carType,
                                 @"frameno" : [_jfModel.vinNum uppercaseString],
                                 @"cardno" : [_jfModel.driveNum uppercaseString],
                                 //                             @"driverfileno":_jfModel.recordNum,
                                 @"trafficinsno" : _jfModel.bdhNum,
                                 @"driverlicence" : _jfModel.driveNum,
                                 @"dutytype" : _partyAGroup.selectedIndex,
                                 @"legalabbreviation" : jfLegalabbreviation,
                                 @"party" : @"1" },
                              @{ @"carownname" : _yfModel.name,
                                 @"carownphone" : _yfModel.phoneNum,
                                 @"casecarno" : _yfModel.carNum,
                                 @"cartype" : _yfModel.carType,
                                 @"frameno" : [_yfModel.vinNum uppercaseString],
                                 @"cardno" : [_yfModel.driveNum uppercaseString],
                                 //                             @"driverfileno":_yfModel.recordNum,
                                 @"trafficinsno" : _yfModel.bdhNum,
                                 @"driverlicence" : _yfModel.driveNum,
                                 @"dutytype" : _partyBGroup.selectedIndex,
                                 @"legalabbreviation" : yfLegalabbreviation,
                                 @"party" : @"0" } ];
            
            [bean setValue:arr forKey:@"casecarlist"];
            
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [LSHttpManager requestUrl:HNServiceURL serviceName:@"jjappiossubmitCaseInfor" parameters:bean complete:^(id result, ResultType resultType) {
                
                [hud hideAnimated:YES];
                if (result)
                {
                    NSLog(@"%@", JsonResult);
                }
                
                if ([result[@"restate"] isEqualToString:@"1"])
                {
                    //协警
                    if (GlobleInstance.userType == AuxiliaryPolice)
                    {
                        if (isArgue)
                        {
                            //有争议 -> 远程定责
                            WaitDutyViewController *vc = [WaitDutyViewController new];
                            GlobleInstance.jfModel = _jfModel;
                            GlobleInstance.yfModel = _yfModel;
                            [self.navigationController pushViewController:vc animated:YES];
                        }
                        else
                        {
                            //无争议 -> 生成协议书
                            JFCreateProtocolVC *vc = [JFCreateProtocolVC new];
                            vc.jfModel = _jfModel;
                            vc.yfModel = _yfModel;
                            vc.jfDutyType = _partyAGroup.selectedIndex;
                            vc.yfDutyType = _partyBGroup.selectedIndex;
                            [self.navigationController pushViewController:vc animated:YES];
                        }
                    }
                    
                    //交警
                    else
                    {
                        JFCreateProtocolVC *vc = [JFCreateProtocolVC new];
                        vc.jfModel = _jfModel;
                        vc.yfModel = _yfModel;
                        vc.jfDutyType = _partyAGroup.selectedIndex;
                        vc.yfDutyType = _partyBGroup.selectedIndex;
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                }
                
                else if ([result[@"restate"] isEqualToString:@"-12"]) {
                    
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示"message:result[@"redes"] preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定"style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        
                    }];
                    
                    
                    [alertController addAction:okAction];
                    
                    [self presentViewController:alertController animated:YES completion:nil];
                }
                
                else
                {
                    SHOWALERT(result[@"redes"]);
                }
                
            }];
            
        }];
        
    }];
    [customView addSubview:confirmBtn];
    
    SRBlockButton *cancelBtn = [[SRBlockButton alloc] initWithFrame:CGRectMake(confirmBtn.maxX + 1, lab.maxY + 21, customView.width / 2, 60) title:@"返回" titleColor:color handleBlock:^(SRBlockButton *btn) {
        
        [jcAlert dismissWithCompletion:^{
            
        }];
        
    }];
    [customView addSubview:cancelBtn];
    
    jcAlert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:YES];
    [jcAlert show];
}
@end
